package cn.gzjp.modules.logis.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.security.acl.Owner;
import java.util.Date;
import java.util.List;

import cn.gzjp.common.mapper.JsonMapper;
import cn.gzjp.common.utils.WebUtil;
import cn.gzjp.common.web.AjaxResult;
import cn.gzjp.modules.logis.entity.LogisUser;
import cn.gzjp.modules.logis.service.LogisUserService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import cn.gzjp.common.utils.DateUtils;
import cn.gzjp.common.utils.MyBeanUtils;
import cn.gzjp.common.persistence.Page;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.common.utils.StringUtils;
import cn.gzjp.common.utils.excel.ExportExcel;
import cn.gzjp.common.utils.excel.ImportExcel;
import cn.gzjp.modules.logis.entity.LogisCar;
import cn.gzjp.modules.logis.service.LogisCarService;

/**
 * 司机车辆Controller
 * @author zengcp
 * @version 2018-04-03
 */
@Controller
@RequestMapping(value = "${adminPath}/logis/logisCar")
public class LogisCarController extends BaseController {

	@Autowired
	private LogisCarService logisCarService;
	@Autowired
	private LogisUserService logisUserService;
	
	
	/**
	 * 司机车辆列表页面
	 */
	@RequiresPermissions("logis:logisCar:list")
	@RequestMapping(value = {"list", ""})
	public String list(LogisCar logisCar, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<LogisCar> page = logisCarService.findPage(new Page<LogisCar>(request, response), logisCar); 
		model.addAttribute("page", page);
		return "modules/logis/logisCarList";
	}


	/**
	 * 车辆列表
	 */
	@RequiresPermissions("logis:logisCar:list")
	@RequestMapping(value = "carList")
	public String carList(LogisCar logisCar, HttpServletRequest request, HttpServletResponse response, Model model) {
		logisCar.setCarStatus(1);
		Page<LogisCar> page = logisCarService.findPage(new Page<LogisCar>(request, response), logisCar);
		model.addAttribute("page", page);
		return "modules/logis/logisCarList2";
	}

	/**
	 * 查看，增加，编辑司机车辆表单页面
	 */
	@RequiresPermissions(value={"logis:logisCar:view","logis:logisCar:add","logis:logisCar:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(LogisCar logisCar, Model model) {
		model.addAttribute("logisCar", logisCar);
		return "modules/logis/logisCarForm";
	}

	/**
	 * 保存司机车辆
	 */
	@RequiresPermissions(value={"logis:logisCar:add","logis:logisCar:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(LogisCar logisCar, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, logisCar)){
			return form(logisCar, model);
		}
		if(!logisCar.getIsNewRecord()){//编辑表单保存
			LogisCar t = logisCarService.get(logisCar.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(logisCar, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			logisCarService.save(t);//保存
			LogisUser user = logisUserService.get(t.getId());
			user.setLicensePlate(t.getLicensePlate());
			user.setRealName(t.getRealName());
			logisUserService.save(user);
		}else{//新增表单保存
			logisCarService.save(logisCar);//保存
		}
		addMessage(redirectAttributes, "保存司机车辆成功");
		return redirect("/logis/logisCar/?repage");
	}


    /**
     * 确认 confirm
     */
    @RequestMapping(value = "confirm", method=RequestMethod.POST)
    @ResponseBody
    public String confirm(String id,String licensePlate,String models,String owner,String address,String vin,String registDate,String issuingDate,String masterDriver) {
        AjaxResult result = new AjaxResult(true,"操作成功");
        LogisCar logisCar = logisCarService.get(id);
        logisCar.setLicensePlate(licensePlate);
        logisCar.setModels(models);
        logisCar.setAddress(address);
        logisCar.setVin(vin);
        logisCar.setRegistDate(registDate);
        logisCar.setIssuingDate(issuingDate);
        //logisCar.setCarStatus(1);
        logisCar.setMasterDriver(masterDriver);
        logisCar.setOwner(owner);
        logisCarService.save(logisCar);
        return JsonMapper.getInstance().toJson(result);
    }

	/**
	 * 审核通过
	 */
	@RequestMapping(value = "auditPass", method=RequestMethod.GET)
	public String auditPass(String id,RedirectAttributes redirectAttributes) {
		LogisCar logisCar = logisCarService.get(id);
		logisCar.setCarStatus(1);
		logisCar.setCarRefusalReason("");
		logisCarService.save(logisCar);
		addMessage(redirectAttributes, "审核通过操作成功");
		return redirect("/logis/logisCar/?repage");
	}
	/**
	 * 审核拒绝
	 */
	@RequestMapping(value = "auditRefuse", method=RequestMethod.GET)
	public String auditRefuse(String id,String carRefusalReason,RedirectAttributes redirectAttributes) {
		LogisCar logisCar = logisCarService.get(id);
		logisCar.setCarStatus(2);
		logisCar.setCarRefusalReason(carRefusalReason);
		logisCarService.save(logisCar);
		addMessage(redirectAttributes, "审核拒绝操作成功");
		return redirect("/logis/logisCar/?repage");
	}


    /**
	 * 删除司机车辆
	 */
	@RequiresPermissions("logis:logisCar:del")
	@RequestMapping(value = "delete")
	public String delete(LogisCar logisCar, RedirectAttributes redirectAttributes) {
		logisCarService.delete(logisCar);
		addMessage(redirectAttributes, "删除司机车辆成功");
		return redirect("/logis/logisCar/?repage");
	}
	
	/**
	 * 批量删除司机车辆
	 */
	@RequiresPermissions("logis:logisCar:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			logisCarService.delete(logisCarService.get(id));
		}
		addMessage(redirectAttributes, "删除司机车辆成功");
		return redirect("/logis/logisCar/?repage");
	}
	
	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("logis:logisCar:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(LogisCar logisCar, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "司机车辆"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<LogisCar> page = logisCarService.findPage(new Page<LogisCar>(request, response, -1), logisCar);
    		new ExportExcel("司机车辆", LogisCar.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出司机车辆记录失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisCar/?repage");
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("logis:logisCar:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<LogisCar> list = ei.getDataList(LogisCar.class);
			for (LogisCar logisCar : list){
				try{
					logisCarService.save(logisCar);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条司机车辆记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条司机车辆记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入司机车辆失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisCar/?repage");
    }
	
	/**
	 * 下载导入司机车辆数据模板
	 */
	@RequiresPermissions("logis:logisCar:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "司机车辆数据导入模板.xlsx";
    		List<LogisCar> list = Lists.newArrayList(); 
    		new ExportExcel("司机车辆数据", LogisCar.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return redirect("/logis/logisCar/?repage");
    }
	@ModelAttribute
	public LogisCar get(@RequestParam(required=false) String id) {
		LogisCar entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = logisCarService.get(id);
		}
		if (entity == null){
			entity = new LogisCar();
		}
		return entity;
	}
	

}